import { Toast } from 'vant';
import type { ToastOptions } from 'vant';
// import { debounce } from 'lodash';
import { debounce } from '@/utils/share';

class LoadingManage {
  static loadingCount = 0;

  static loading = false;

  static preventLoading = false;

  static toastWithCallBackOptions: ToastOptions = {
    message: '网络连接错误, 请稍后重试',
    forbidClick: true,
    duration: 2000,
  };

  startLoading = async () => {
    LoadingManage.loadingCount += 1;
    if (!LoadingManage.loading && !LoadingManage.preventLoading) {
      LoadingManage.loading = true;
      Toast.loading({
        message: '加载中...',
        forbidClick: true,
        duration: 0,
      });
    }
  };

  closeLoading = debounce(() => {
    LoadingManage.loadingCount -= 1;
    if (LoadingManage.loadingCount <= 0 && LoadingManage.loading) {
      Toast.clear();
      LoadingManage.loading = false;
    }
  }, 500);

  toastWithCallBack = async (opts: ToastOptions = {}, callback: undefined | Function, showErrorToast?: any) => {
    LoadingManage.preventLoading = true;
    const options = { ...LoadingManage.toastWithCallBackOptions, ...opts };
    if (LoadingManage.loading) {
      Toast.clear();
      LoadingManage.loading = false;
    }
    if (showErrorToast) {
      Toast(options);
      setTimeout(() => {
        LoadingManage.preventLoading = false;
        typeof callback === 'function' && callback();
      }, options.duration);
    } else {
      LoadingManage.preventLoading = false;
      typeof callback === 'function' && callback();
    }
  };
}

export default new LoadingManage();
